﻿using System.Reflection;
using System.Web.Http;
using Abp.Application.Services;
using Abp.Configuration.Startup;
using Abp.Modules;
using Abp.WebApi;
using Swashbuckle.Application;
using System.Linq;
using System;
using System.IO;

namespace ShiTong.PhoneBook.Api
{
    [DependsOn(typeof(AbpWebApiModule), typeof(PhoneBookApplicationModule))]
    public class PhoneBookWebApiModule : AbpModule
    {
        public override void Initialize()
        {
            IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());

            Configuration.Modules.AbpWebApi().DynamicApiControllerBuilder
                .ForAll<IApplicationService>(typeof(PhoneBookApplicationModule).Assembly, "app")
                .Build();

            Configuration.Modules.AbpWebApi().HttpConfiguration.Filters.Add(new HostAuthenticationFilter("Bearer"));
            ConfigureSwaggerUi();
        }

        /// <summary>
        /// 配置SwaggerUi
        /// </summary>
        private void ConfigureSwaggerUi()
        {
            Configuration.Modules.AbpWebApi().HttpConfiguration
                .EnableSwagger(c =>
                {
                    c.SingleApiVersion("v1", "ShiTong.PhoneBookAPI文档");
                    c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
                    //将application层中的注释添加到SwaggerUI中
                    var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;

                    var commentsFileName = "bin//" + typeof(PhoneBookApplicationModule).Assembly.GetName().Name + ".XML";
                    var commentsFile = Path.Combine(baseDirectory, commentsFileName);
                    //将注释的XML文档添加到SwaggerUI中
                    c.IncludeXmlComments(commentsFile);
                })
                .EnableSwaggerUi("api/{*assetPath}",b=> {
                    b.InjectJavaScript(Assembly.GetAssembly(typeof(PhoneBookWebApiModule)), "ShiTong.PhoneBook.scripts.swagger.js");
                });
                //.EnableSwaggerUi("api/{*assetPath}", b =>
                // {
                //     b.InjectJavaScript(Assembly.GetAssembly(typeof(PhoneBookWebApiModule)),
                //     "ShiTong.PhoneBook.scripts.swagger.js");
                // });

        }
        public override void PreInitialize()
        {
            ////关闭跨站脚本攻击
            Configuration.Modules.AbpWeb().AntiForgery.IsEnabled = false;
        }

    }
}
